﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Objects;

namespace DAL
{
    public class Factory<T> : IFactory<T> where T : class
    {
        IObjectSet<T> _objectSet;
        ObjectContext _objectContext;

        public Factory(ObjectContext objectContext)
        {
            _objectSet = objectContext.CreateObjectSet<T>();
            _objectContext = objectContext;
        }

        public IQueryable<T> AsQueryable()
        {
            return _objectSet;
        }

        public IEnumerable<T> GetAll()
        {
            return _objectSet.ToList();
        }

        public IEnumerable<T> Find(Expression<Func<T, bool>> where)
        {
            return _objectSet.Where(where);
        }

        public T Single(Expression<Func<T, bool>> where)
        {
            return Find(where).First();
        }

        public void Delete(T entity)
        {
            _objectSet.DeleteObject(entity);
        }

        public void Add(T entity)
        {
            _objectSet.AddObject(entity);
        }

        public void Attach(T entity)
        {
            _objectSet.Attach(entity);
        }

        public void Dispose()
        {
            if (_objectContext != null)
            {
                _objectContext.Dispose();
            }
            GC.SuppressFinalize(this);
        }

        public void Commit()
        {
            _objectContext.SaveChanges();
        }
    }
}
